'''
Description: 
Author: Zilu
Date: 2021-11-10 15:40:31
Version: 
LastEditTime: 2021-11-10 16:16:24
LastEditors: Zilu
'''

# Process可以分布到多台机器上，而Thread最多只能分布到同一台机器的多个CPU上
# multiprocessing 中的managers模块可以把多进程分布到多台机器上

from multiprocessing import managers
import random, time, queue
from multiprocessing.managers import BaseManager

# 发送任务的队列
taskQueue = queue.Queue()
resultQueue = queue.Queue()

def returnTaskQueue():
    global taskQueue
    return taskQueue

def returnResultQueue():
    global resultQueue
    return resultQueue

class QueueManager(BaseManager):
    pass

if __name__ == '__main__':
    # 把两个Queue都注册到网络上，callable参数关联了Queue对象
    # Linux 下可以用lambda 但是windows下不能pickle lambda
    QueueManager.register('getTaskQueue', callable=returnTaskQueue)
    QueueManager.register('getResultQueue', callable=returnResultQueue)
    # 绑定端口5000，设置验证码“abc”：
    manager = QueueManager(address=('127.0.0.1', 5000), authkey=b'abc')
    # 启动Queue
    manager.start()
    # 获得网络访问的Queue对象
    task = manager.getTaskQueue()
    result = manager.getResultQueue()

    # 放几个任务进去：
    for i in range(10):
        n = random.randint(0,1000)
        print('Put task %d...' % n)
        task.put(n)

    # 从result队列读取结果
    print('Try get results...')
    for i in range(10):
        r = result.get(timeout=10)
        print('Result: %s' % r)

    # 关闭
    manager.shutdown()
    print('Master exit.')



